package cn.stylefeng.guns.modular.system.controller;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.modular.system.controller.dto.ZapplicationTask;
import cn.stylefeng.guns.modular.system.entity.Srecharge;
import cn.stylefeng.guns.modular.system.entity.ZApplicaionAudit;
import cn.stylefeng.guns.modular.system.entity.ZApplication;
import cn.stylefeng.guns.modular.system.mapper.ZApplicationMapper;
import cn.stylefeng.guns.modular.system.model.params.ZApplicaionAuditParam;
import cn.stylefeng.guns.modular.system.model.params.ZApplicationParam;
import cn.stylefeng.guns.modular.system.service.ZApplicaionAuditService;
import cn.stylefeng.guns.modular.system.service.ZApplicationService;
import cn.stylefeng.guns.sys.core.shiro.ShiroKit;
import cn.stylefeng.guns.sys.core.shiro.service.UserAuthService;
import cn.stylefeng.guns.sys.core.util.common.*;
import cn.stylefeng.guns.sys.modular.system.service.DeptService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.print.attribute.standard.ReferenceUriSchemesSupported;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.FileNotFoundException;
import java.lang.reflect.MalformedParameterizedTypeException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 控制器
 * 装修申请
 * @author yl
 * @Date 2019-07-09 20:39:18
 */
@Controller
@RequestMapping("/zApplication")
public class ZApplicationController extends BaseController {

    private String PREFIX = "/zApplication";

    @Autowired
    private ZApplicationService zApplicationService;
    @Autowired
    private ZApplicationMapper zApplicationMapper;
    @Resource
    private RuntimeService runtimeService;
    @Resource
    private TaskService taskService;
    @Resource
    private IdentityService identityService;
    @Autowired
    private UserService userService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private ZApplicaionAuditService zApplicaionAuditService;


    /**
     * 跳转到主页面
     *
     * @author yl
     * @Date 2019-07-09
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/zApplication.html";
    }


    /**
     * 跳转到主页面
     *
     * @author yl
     * @Date 2019-07-09
     */
    @RequestMapping("/indexCheck")
    public String indexCheck() {
        return PREFIX + "/zApplicationCheck.html";
    }




    /**
     * 新增页面
     *
     * @author yl
     * @Date 2019-07-09
     */
    @RequestMapping("/add")
    public String add(Model model) {
        model.addAttribute("username",ShiroKit.getUserNotNull().getName());
        model.addAttribute("deptName",deptService.getById(ShiroKit.getUserNotNull().getDeptId()).getSimpleName());
        return PREFIX + "/zApplication_add.html";
    }

    /**
     * 编辑页面
     *
     * @author yl
     * @Date 2019-07-09
     */
    @RequestMapping("/edit")
    public String edit(Model model,Long id, HttpSession session, String taskId) {
        model.addAttribute("username",ShiroKit.getUserNotNull().getName());
        model.addAttribute("deptName",deptService.getById(ShiroKit.getUserNotNull().getDeptId()).getSimpleName());
        model.addAttribute("ids",id);
        session.setAttribute("z_application_id",id);
        model.addAttribute("taskId",taskId);
        return PREFIX + "/zApplication_edit.html";
    }

    /**
     * 新增接口
     *
     * @author yl
     * @Date 2019-07-09
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(ZApplicationParam zApplicationParam) {

        zApplicationParam.setDate(new Date());
        //保存登录人的id
        zApplicationParam.setApplicationId(ShiroKit.getUserNotNull().getId());
        //保存附件地址以及名称
        zApplicationParam.setEnclosu(SystemConstant.TENCENT_URL+zApplicationParam.getEnclosu());

        identityService.setAuthenticatedUserId(ShiroKit.getUserNotNull().getId() +"");
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(SystemConstant.pc_zhuangxiu);
        zApplicationParam.setProcessInstanceId(processInstance.getId());

        zApplicationParam.setDecorationStatus("0");
        this.zApplicationService.add(zApplicationParam);

        //开启一个流程
        Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        taskService.setAssignee(task.getId(),ShiroKit.getUserNotNull().getId() +"");
        taskService.complete(task.getId());
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author yl
     * @Date 2019-07-09
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(ZApplicationParam zApplicationParam) {
        ZApplication zApplication = new ZApplication();
        BeanUtils.copyProperties(zApplicationParam,zApplication);
        zApplication.setDate(new Date());
        //zApplicationMapper.insert(zApplication);
        //保存登录人的id
        zApplicationParam.setApplicationId(ShiroKit.getUserNotNull().getId());
        //保存附件地址以及名称
        zApplicationParam.setEnclosu(SystemConstant.TENCENT_URL+zApplicationParam.getEnclosu());
        this.zApplicationService.update(zApplicationParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author yl
     * @Date 2019-07-09
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(ZApplicationParam zApplicationParam) {
        this.zApplicationService.delete(zApplicationParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author yl
     * @Date 2019-07-09
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(ZApplicationParam zApplicationParam) {
        ZApplication detail = this.zApplicationService.getById(zApplicationParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author yl
     * @Date 2019-07-09
     */
//    @ResponseBody
//    @RequestMapping("/list")
//    public LayuiPageInfo list(ZApplicationParam zApplicationParam) {
//        return this.zApplicationService.findPageBySpec(zApplicationParam);
//    }


    /**
     * 查询列表
     * @Date 2019-07-09
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo QueryList(String condition) {
        LayuiPageInfo lyf = new LayuiPageInfo();
        lyf.setData(zApplicationService.QueryList(condition));
        return lyf;
    }

    @ResponseBody
    @RequestMapping("/checkList")
    public LayuiPageInfo checkList(){

        List<Task> tasks = taskService.createTaskQuery().processDefinitionKey(SystemConstant.pc_zhuangxiu).taskCandidateUser(ShiroKit.getUserNotNull().getId() +"").list();
        if (tasks.size() == 0){
            return  new LayuiPageInfo();
        }
        List<ZapplicationTask> zapplicationTasks = tasks.stream().filter(task -> zApplicationService.getOne(new QueryWrapper<ZApplication>()
                .lambda().eq(ZApplication::getProcessInstanceId,task.getProcessInstanceId()))!= null).map(task -> {
            ZapplicationTask zapplicationTask = new ZapplicationTask();
           ZApplication application = zApplicationService.getOne(new QueryWrapper<ZApplication>()
          .lambda().eq(ZApplication::getProcessInstanceId,task.getProcessInstanceId()));
           BeanUtils.copyProperties(application,zapplicationTask);
           zapplicationTask.setUserName(userService.getById(application.getApplicationId()).getName());
           zapplicationTask.setDeptName(deptService.getById(userService.getById(application.getApplicationId()).getDeptId()).getSimpleName());
           zapplicationTask.setTaskId(task.getId());
           zapplicationTask.setProcessInstanceId(task.getProcessInstanceId());
           return zapplicationTask;
     }).collect(Collectors.toList());

     LayuiPageInfo layuiPageInfo = new LayuiPageInfo();
     layuiPageInfo.setCount(zapplicationTasks.size());
     layuiPageInfo.setData(zapplicationTasks);
     return layuiPageInfo;
    }

    /**
     * 跳转审核页面
     * @param id
     * @param taskId
     * @return
     */
    @RequestMapping("/checkIndex")
    public String checkIndex(Long id,String taskId){
        return  PREFIX + "/check.html";
    }

    /**
     * 审核方法
     */
    @ResponseBody
    @RequestMapping("/check")
    public ResponseData check(ZApplicaionAuditParam applicaionAuditParam, ZApplicationParam zApplicationParam){

        ZApplicaionAudit zapplicationTask = new ZApplicaionAudit();
        BeanUtils.copyProperties(applicaionAuditParam,zapplicationTask);
        Task task = taskService.createTaskQuery().taskId(applicaionAuditParam.getTaskId()).singleResult();
        zapplicationTask.setProcessInstanceId(task.getProcessInstanceId());
        zapplicationTask.setTaskId(task.getId());
        zapplicationTask.setUserId(ShiroKit.getUserNotNull().getId());
        zapplicationTask.setzApplicationId(zApplicationParam.getId());
        zapplicationTask.setAuditStatus(applicaionAuditParam.getAuditStatus());

        zApplicaionAuditService.save(zapplicationTask);

        //修改审核状态
        zApplicationParam.setDecorationStatus("1");
        zApplicationParam.setId(zApplicationParam.getId());
        zApplicationService.update(zApplicationParam);

        Map<String,Object> map = new HashMap<>();
        map.put("status",applicaionAuditParam.getAuditStatus());
        taskService.complete(task.getId(),map);
        return  ResponseData.success();
    }





    /*---------------------上传文件接口------------------------------------------*/
    @RequestMapping(method = RequestMethod.POST, path = "/UploadFileShi")
    @ResponseBody
    public ResponseData UploadFileShi(@RequestPart("file") MultipartFile file) throws FileNotFoundException {
        if (ToolUtil.isEmpty(file)){
            return  ResponseData.error(201,"上传失败，图片为空");
        }else{
            ResponseMsg msg = UploadFileShi.uploadFile(file);
            if (msg.getStatus() == 10001){
                UploadResult result = (UploadResult) msg.getResult();
                return  ResponseData.success(200,"上传成功",result.getPath());
            }else {
                return  ResponseData.error(202,"上传失败，图片格式错误");
            }
        }
    }




    /**
     * 根据id查询数据
     */
    @ResponseBody
    @RequestMapping("/QueryZApplicationID")
    public LayuiPageInfo QueryZApplicationID(HttpSession session) {
        Object id = session.getAttribute("z_application_id");
        long ids = Long.valueOf(String.valueOf(id));
        LayuiPageInfo lyf = new LayuiPageInfo();
        lyf.setData(zApplicationService.QueryZApplicationID(ids));
        return lyf;
    }





    /**
     * 跳转到审核页面
     *
     * @author yl
     * @Date 2019-07-09
     */
    @RequestMapping("/zApplication_shenghe")
    public String shenghe(String id,String taskId,Model model) {

        super.setAttr("id", id);
        super.setAttr("taskId", taskId);//任务id
        model.addAttribute("id", id);
        model.addAttribute("taskId", taskId);
        return PREFIX + "/zApplication_shenghe.html";
    }
















}


